package starter.tool;

import static com.bowlong.util.Log.e2s;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import starter.game.netty.GameTcpHandler;

import com.bowlong.util.Log;

/**
 * @Description ：关闭服务器
 */
public class Shutdown extends Thread {
	public ServerSocket ssocket = null;

	public Shutdown(int port) throws Exception {
		InetAddress addr = InetAddress.getByName("127.0.0.1");

		try (Socket socket = new Socket(addr, port);) { // 关闭其他进程
			socket.getInputStream().read();
			Thread.sleep(1000);
		} catch (Exception e) {
		}

		ssocket = new ServerSocket(port, 2, addr);
	}

	@Override
	public void run() {
		try {
			ssocket.accept();

			// 需要等待数据库异步处理完成。
			//
			// 检查数据是否全部已经保存了
			int tm = 5; // 最多暂停5s
			while (true) {
				Log.info("wait:" + tm);
				if (tm-- <= 0)
					break;

				Thread.sleep(1000);
			}
			// 停服之前释放本服务器全部的session
			GameTcpHandler.closeAll();
			System.exit(1);
		} catch (Exception e) {
			Log.warn(e2s(e));
		}
	}
}
